<template>
    <div class="wrapper">
		<!-- 顶部应用栏 -->
		<header class="mdc-top-app-bar">
			<div class="mdc-top-app-bar__row">
				<section class="mdc-top-app-bar__section mdc-top-app-bar__section--align-start">
					<BackButton />
					<h1 class="mdc-top-app-bar__title">编辑个人信息</h1>
				</section>
			</div>
		</header>

		<!-- 主要内容区域 -->
		<div class="main-content">
			<!-- 头像编辑卡片 -->
			<div class="avatar-card">
				<div class="card-header">
					<i class="material-icons">account_circle</i>
					<h5>头像</h5>
				</div>
				<div class="avatar-section">
					<input 
						type="file" 
						ref="fileInput"
						@change="onFileChange" 
						accept="image/*" 
						class="file-input"
						id="avatar-input"
					>
					<label for="avatar-input" class="avatar-preview">
						<img 
							v-if="userImg && !avatarError"
							:src="getImg(userImg)" 
							@error="handleImageError"
							class="avatar-image"
							alt="用户头像"
						>
						<i v-else class="material-icons default-avatar-icon">account_circle</i>
						<div class="avatar-overlay">
							<i class="material-icons">camera_alt</i>
							<span>点击更换</span>
						</div>
					</label>
					<label for="avatar-input" class="upload-button">
						<i class="material-icons">photo_library</i>
						<span>选择图片</span>
					</label>
				</div>
			</div>

			<!-- 个人信息编辑卡片 -->
			<div class="info-card">
				<div class="card-header">
					<i class="material-icons">edit</i>
					<h5>个人信息</h5>
				</div>
				<div class="form-section">
					<div class="form-group">
						<label for="userName" class="form-label">
							<i class="material-icons">person</i>
							<span>昵称</span>
						</label>
						<input 
							type="text" 
							id="userName"
							v-model="userName" 
							placeholder="请输入昵称" 
							class="form-input"
							maxlength="20"
						/>
					</div>
				</div>
			</div>

			<!-- 提交按钮 -->
			<button class="submit-button" @click="submitEdit" :disabled="submitting">
				<i class="material-icons" v-if="!submitting">check</i>
				<i class="material-icons rotating" v-else>refresh</i>
				<span>{{ submitting ? '提交中...' : '保存修改' }}</span>
			</button>
		</div>
    </div>
</template>
  
<script>
    import BackButton from '../components/BackButton.vue';
  
    export default {
        name: 'ChangeInfo',
        data() {    
            return {
				userId: this.$route.query.userId,
				userImg:'',
				userName:'',
				selectedFile: null,
				avatarError: false,
				submitting: false
            };
        },
        methods: {
            getImg(path){
				if(!path) return this.getDefaultImage();
				// 如果是完整的HTTP URL，直接返回
				if(path.startsWith('http')) return path;
				// 如果是 base64 格式，直接返回
				if(path.startsWith('data:image')) return path;
				// 如果是相对路径（以/开头），拼接服务器地址
				if(path.startsWith('/')) {
					// 如果已经是 /img/ 开头，直接拼接
					if(path.startsWith('/img/')) {
						return 'http://localhost:8888' + path;
					}
					// 如果是其他路径（如 /2024-10-26/xxx.jpg），需要添加 /img 前缀
					return 'http://localhost:8888/img' + path;
				}
				// 其他情况，添加服务器前缀和路径分隔符
				return 'http://localhost:8888/img/' + path;
			},
			getDefaultImage(){
				// 返回一个包含食物emoji的SVG图片
				const svg = '<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200" viewBox="0 0 200 200"><rect width="200" height="200" fill="#f5f5f5" rx="10"/><text x="100" y="100" font-size="80" text-anchor="middle" dominant-baseline="central">🍕</text></svg>';
				return 'data:image/svg+xml;base64,' + btoa(unescape(encodeURIComponent(svg)));
			},
			handleImageError(event){
				event.target.src = this.getDefaultImage();
			},
		onFileChange(event) {
			const file = event.target.files[0];
			if (!file) return;
			
			// 验证文件类型
			if (!file.type.startsWith('image/')) {
				this.$toast?.error('请选择图片文件');
				return;
			}
			
			// 验证文件大小（限制为5MB）
			if (file.size > 5 * 1024 * 1024) {
				this.$toast?.error('图片大小不能超过5MB');
				return;
			}
			
			this.selectedFile = file;
			this.avatarError = false;
			this.uploadImage();
		},
		uploadImage() {
			if (!this.selectedFile) return;
			
			let formData = new FormData();
			formData.append('file', this.selectedFile);

			this.$toast?.info('正在上传图片...');
			
			this.$axios.post('FileController/user/img', formData, {
				headers: {
					'Content-Type': 'multipart/form-data'
				}
			})
			.then(response => {
				if (response.data.code === '200') {
					this.userImg = response.data.result;
					this.$toast?.success('头像上传成功');
				} else {
					this.$toast?.error('图片上传失败');
				}
			})
			.catch(error => {
				console.error('图片上传错误', error);
				this.$toast?.error('图片上传失败，请重试');
			});
		},
		submitEdit() {
			// 验证昵称
			if (!this.userName || this.userName.trim() === '') {
				this.$toast?.error('请输入昵称');
				return;
			}
			
			if (this.userName.trim().length < 2) {
				this.$toast?.error('昵称至少需要2个字符');
				return;
			}
			
			this.submitting = true;
			
			this.$axios.post('UserController/user/updateInfo', this.$qs.stringify({
				userId: this.userId,
				userName: this.userName.trim(),
				userImg: this.userImg,
			}))
			.then(response => {
				if (response.data.code === '200') {
					this.$toast?.success('个人信息更新成功');
					// 更新sessionStorage中的用户信息
					let user = this.$getSessionStorage('user');
					if (user) {
						user.userName = this.userName.trim();
						user.userImg = this.userImg;
						this.$setSessionStorage('user', user);
					}
					setTimeout(() => {
						this.$router.go(-1);
					}, 1000);
				} else {
					this.$toast?.error('更新失败：' + (response.data.message || '未知错误'));
				}
			})
			.catch(error => {
				console.error('提交错误', error);
				this.$toast?.error('更新失败，请重试');
			})
			.finally(() => {
				this.submitting = false;
			});
		}
        },
        components: {
            BackButton
        },
        created() {
            this.$axios.post('UserController/user/info',this.$qs.stringify({
				userId : this.userId
			})).then(response=>{
				if(response.data.code=='200'){
					let re=response.data.result;
					this.userName=re.userName;
					this.userImg=re.userImg;
				}
			}).catch(error=>{
				console.error(error);
			});
        }
    };
</script>
  
<style scoped>
    .wrapper {
		min-height: 100vh;
		background-color: #f5f5f5;
		display: flex;
		flex-direction: column;
	}

	/* 顶部应用栏 */
	.mdc-top-app-bar {
		background-color: #1976D2;
		color: white;
		position: sticky;
		top: 0;
		z-index: 100;
		box-shadow: 0 2px 4px rgba(0,0,0,0.1);
	}

	.mdc-top-app-bar__row {
		display: flex;
		align-items: center;
		height: 72px;
		padding: 0 20px;
	}

	.mdc-top-app-bar__section {
		display: flex;
		align-items: center;
		gap: 16px;
		flex-direction: row;
	}

	.mdc-top-app-bar__title {
		font-size: 22px;
		font-weight: 500;
		margin: 0;
		white-space: nowrap;
		line-height: 1;
	}

	/* 主要内容区域 */
	.main-content {
		padding: 20px 16px;
		padding-bottom: 40px;
	}

	/* 卡片样式 */
	.avatar-card,
	.info-card {
		background-color: white;
		border-radius: 16px;
		box-shadow: 0 2px 12px rgba(0,0,0,0.08);
		overflow: hidden;
		margin-bottom: 20px;
	}

	.card-header {
		background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
		padding: 16px 20px;
		display: flex;
		align-items: center;
		gap: 12px;
	}

	.card-header .material-icons {
		font-size: 24px;
		color: #667eea;
	}

	.card-header h5 {
		font-size: 16px;
		font-weight: 600;
		color: #333;
		margin: 0;
	}

	/* 头像部分 */
	.avatar-section {
		padding: 24px 20px;
		display: flex;
		flex-direction: column;
		align-items: center;
		gap: 20px;
	}

	.avatar-preview {
		position: relative;
		width: 120px;
		height: 120px;
		border-radius: 50%;
		overflow: hidden;
		cursor: pointer;
		transition: all 0.3s ease;
		box-shadow: 0 4px 16px rgba(0,0,0,0.15);
	}

	.avatar-preview:hover {
		transform: scale(1.05);
		box-shadow: 0 6px 20px rgba(0,0,0,0.2);
	}

	.avatar-preview:hover .avatar-overlay {
		opacity: 1;
	}

	.avatar-image {
		width: 100%;
		height: 100%;
		object-fit: cover;
	}

	.default-avatar-icon {
		width: 100%;
		height: 100%;
		font-size: 120px !important;
		color: #ddd;
		display: flex;
		align-items: center;
		justify-content: center;
		background-color: #f5f5f5;
	}

	.avatar-overlay {
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(0,0,0,0.6);
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		gap: 8px;
		color: white;
		opacity: 0;
		transition: opacity 0.3s ease;
	}

	.avatar-overlay .material-icons {
		font-size: 32px;
	}

	.avatar-overlay span {
		font-size: 14px;
		font-weight: 500;
	}

	.file-input {
		display: none;
	}

	.upload-button {
		display: flex;
		align-items: center;
		gap: 8px;
		padding: 12px 24px;
		background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
		color: white;
		border-radius: 24px;
		cursor: pointer;
		font-size: 14px;
		font-weight: 500;
		transition: all 0.3s ease;
		box-shadow: 0 2px 8px rgba(102,126,234,0.3);
	}

	.upload-button:hover {
		transform: translateY(-2px);
		box-shadow: 0 4px 12px rgba(102,126,234,0.4);
	}

	.upload-button:active {
		transform: translateY(0);
	}

	.upload-button .material-icons {
		font-size: 20px;
	}

	/* 表单部分 */
	.form-section {
		padding: 20px;
	}

	.form-group {
		margin-bottom: 0;
	}

	.form-label {
		display: flex;
		align-items: center;
		gap: 10px;
		font-size: 14px;
		font-weight: 500;
		color: #666;
		margin-bottom: 12px;
	}

	.form-label .material-icons {
		font-size: 20px;
		color: #667eea;
	}

	.form-input {
		width: 100%;
		padding: 14px 16px;
		font-size: 16px;
		border: 2px solid #e0e0e0;
		border-radius: 12px;
		transition: all 0.3s ease;
		background-color: #fafafa;
		box-sizing: border-box;
	}

	.form-input:focus {
		outline: none;
		border-color: #667eea;
		background-color: white;
		box-shadow: 0 0 0 3px rgba(102,126,234,0.1);
	}

	.form-input::placeholder {
		color: #999;
	}

	/* 提交按钮 */
	.submit-button {
		width: 100%;
		padding: 16px;
		background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
		color: white;
		border: none;
		border-radius: 12px;
		font-size: 16px;
		font-weight: 600;
		cursor: pointer;
		display: flex;
		align-items: center;
		justify-content: center;
		gap: 8px;
		box-shadow: 0 4px 12px rgba(102,126,234,0.4);
		transition: all 0.3s ease;
		margin-top: 8px;
	}

	.submit-button:hover:not(:disabled) {
		transform: translateY(-2px);
		box-shadow: 0 6px 16px rgba(102,126,234,0.5);
	}

	.submit-button:active:not(:disabled) {
		transform: translateY(0);
	}

	.submit-button:disabled {
		opacity: 0.6;
		cursor: not-allowed;
	}

	.submit-button .material-icons {
		font-size: 20px;
	}

	.rotating {
		animation: rotate 1s linear infinite;
	}

	@keyframes rotate {
		from {
			transform: rotate(0deg);
		}
		to {
			transform: rotate(360deg);
		}
	}

	/* 响应式设计 */
	@media (max-width: 600px) {
		.main-content {
			padding: 16px 12px;
		}

		.avatar-preview {
			width: 100px;
			height: 100px;
		}

		.default-avatar-icon {
			font-size: 100px !important;
		}
	}
</style>
